<template>
  <div>
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" :width="dialogwidth()" :close-on-click-modal="false"
      :before-close="handleClose">
      <div class="form">
        <!-- 表单输入元件 ----------------------------------------------------------------------------------------->
        <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="120px">
          <div style="width: 450px;margin: auto;">
            <el-form-item>
              <template #label>
                <div style="text-align: right;">采购品来源</div>
              </template>
              <el-select style="width:100%" v-model="ruleForm.faultLevel" filterable placeholder="请选择故障等级">
                <el-option v-for="(item, i) in ['系统内采购品', '系统外采购品']" :key="i" :label="item" :value="i" />
              </el-select>
            </el-form-item>
          </div>
          <el-divider></el-divider>
          <!-- ----------------------------------------------系统内采购品-------------------------------------- -->
          <div v-if="ruleForm.faultLevel == 0">
            <!-- 物料采购查询栏-------------------------------------------------------------------------------- -->
            <div class="search_continer" v-if="spareType == 1">
              <div class="search_continer_title">查询栏</div>
              <div class="search_continer_myInput">
                <el-input v-model="AqueryParams.materialNum" placeholder="请输入物料编号" />
              </div>
              <div class="search_continer_myInput">
                <el-input v-model="AqueryParams.materialName" placeholder="请输入物料名称" />
              </div>
              <el-button type="primary" icon="el-icon-search" @click="handleQueryClick">查询</el-button>
              <el-button icon="el-icon-refresh-left" @click="handleReset">重置</el-button>
            </div>
            <!-- 设备查询栏-------------------------------------------------------------------------------- -->
            <div class="search_continer" v-if="spareType == 0">
              <div class="search_continer_title">查询栏</div>
              <div class="search_continer_myInput">
                <el-input style="width: 300px;margin-left: 30px;" v-model="BqueryParams.equipmentName"
                  placeholder="请输入设备名称" />
              </div>
              <el-button type="primary" icon="el-icon-search" @click="handleQueryClick">查询</el-button>
              <el-button icon="el-icon-refresh-left" @click="handleReset">重置</el-button>
            </div>
            <!-- 提交按钮---------------------------------------------------------------------------------------- -->
            <div class="operation_continer">
              <div class="operation_continer_title">操作栏</div>
              <el-button type="primary" icon="el-icon-circle-plus-outline" @click="handleSubmit">提交</el-button>
            </div>
            <!-- 物料采购表格列表------------------------------------------------------------------------------------------ -->
            <div class="form_table">
              <el-table ref="listPowerSupplyTab" :data="ruleFormList" style="width: 100%"
                @selection-change="handleSelectionChange" v-if="spareType == 1">
                <el-table-column type="selection" width="55" />
                <el-table-column label="序号" width="100">
                  <template slot-scope="scope">
                    <div> {{ scope.$index + 1 }} </div>
                  </template>
                </el-table-column>
                <el-table-column prop="materialNum" label="物料编号" show-overflow-tooltip />
                <el-table-column prop="materialName" label="物料名称" show-overflow-tooltip />
                <el-table-column prop="typeName" label="物料类别" show-overflow-tooltip />
                <el-table-column prop="model" label="物料规格型号" show-overflow-tooltip>
                  <template slot-scope="{row}">
                    <div> {{ row.model || '-' }} </div>
                  </template>
                </el-table-column>
                <el-table-column prop="supplierName" label="物料供应商" show-overflow-tooltip />
                <el-table-column prop="unitName" label="物料单位" show-overflow-tooltip />
                <el-table-column prop="amount" label="物料类型">
                  <template slot-scope="{row}">
                    <dict-tags :options="SparePartsAndConsumables" :value="row.kind" />
                  </template>
                </el-table-column>
                <el-table-column prop="price" label="物料单价（元）" />
                <el-table-column prop="amount" label="物料总库存">
                  <template slot-scope="{row}">
                    <div> {{ row.amount || '0' }} </div>
                  </template>
                </el-table-column>
                <el-table-column prop="remark" label="物料备注" show-overflow-tooltip>
                  <template slot-scope="{row}">
                    <div> {{ row.remark || '-' }} </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <!-- 设备表格列表------------------------------------------------------------------------------------------ -->
            <div class="form_table">
              <el-table ref="listPowerSupplyTab" :data="ruleFormList" style="width: 100%"
                @selection-change="handleSelectionChange" v-if="spareType == 0">
                <el-table-column type="selection" width="55" />
                <el-table-column label="序号" width="100">
                  <template slot-scope="scope">
                    <div> {{ scope.$index + 1 }} </div>
                  </template>
                </el-table-column>
                <el-table-column prop="equipmentName" label="设备名称" show-overflow-tooltip />
                <el-table-column prop="brand" label="设备品牌" show-overflow-tooltip />
                <el-table-column prop="typeName" label="设备类别" show-overflow-tooltip />
                <el-table-column prop="model" label="设备规格型号" show-overflow-tooltip />
                <el-table-column prop="supplierName" label="设备供应商" show-overflow-tooltip />
                <el-table-column prop="unitName" label="设备单位" show-overflow-tooltip />
                <el-table-column label="设备状态">
                  <template slot-scope="{row}">
                    <dict-tag :options="statusFlag" :value="row.status" />
                  </template>
                </el-table-column>
                <el-table-column label="是/否计量设备">
                  <template slot-scope="{row}">
                    <div>{{ ['是', '否'][row.meterageFlag] }} </div>
                  </template>
                </el-table-column>
                <el-table-column label="计量编号" show-overflow-tooltip>
                  <template slot-scope="{row}">
                    {{ row.meterageNum || '-' }}
                  </template>
                </el-table-column>
                <el-table-column prop="remark" label="设备备注" show-overflow-tooltip>
                  <template slot-scope="{row}">
                    {{ row.remark || '-' }}
                  </template>
                </el-table-column>
                <el-table-column prop="remark" label="操作">
                  <template slot-scope="{row}">
                    <el-button size="small" type="primary" icon="el-icon-view" @click="handleSelectImage(row.image)">图片
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <!-- --------------------------------分页器---------------------------------------------------------- -->
            <div class="table_continer_pagination">
              <el-pagination :current-page="pageParams.pageNum" background :page-sizes="[10, 20, 50, 100]"
                :page-size="pageParams.pageSize" layout="total, sizes, prev, pager, next, jumper"
                :total="pagination.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
          </div>
          <!-- ----------------------------------------------系统外采购品-------------------------------------- -->
          <div v-if="ruleForm.faultLevel == 1" style="width: 450px;margin: auto;">
            <!-- ------------------------新增物料组件----------------------- -->
            <supplierA v-if="spareType == 1" @parent_indexA="handleparentindexa" @parent_close="handleClose" />
            <!-- ------------------------新增设备组件----------------------- -->
            <supplierB v-if="spareType == 0" @parent_indexB="handleparentindexb" @parent_close="handleClose" />
          </div>
        </el-form>
        <!-- ----------------------------------------------------------------------------------------------------->
      </div>

    </el-dialog>
    <template v-if="ImageOpen">
      <Dialog-image :src="imageSrc" />
    </template>
  </div>
</template>

<script>
/** 远程添加，修改，获取单个详性接口，获取selector下拉列表的接口，以及时间转换工具函数等 ------------------------------------------------- */
import { supplierlist } from '@/api/maintenance/management/Outsourcing.js'
import { replacementList, equipmentList } from '@/api/purchasing/purchasing'
import { pageCount } from '@/utils/pagination'
import UploadImage from '@/components/upload/index.vue'
import supplierA from './supplier-parent/indexA.vue'
import supplierB from './supplier-parent/indexB.vue'
/** ------------------------------------------------------------------------------------------------------------------------------- */
function processQueryParams (queryParams, pageParams) {
  const params = Object.assign({}, queryParams, pageParams)
  return params
}
/** 表单参数 ------------------------------------------------------------------------------------------------------------------------ */
const ruleForm = {
  faultLevel: 0,//供应商来源（0系统内供应商，1系统外供应商）==> 不做表单数据
}
/** ---------------------------------------------------------------------------------------------------------------------------------- */

export default {
  name: 'Form',
  components: {
    UploadImage,
    supplierA,
    supplierB
  },
  props: {
    parlist: {
      type: Array,
      required: true
    },
  },
  data () {
    return {
      dialogVisible: false,
      ruleForm: Object.assign({}, ruleForm),
      dialogTitle: '添加采购品',
      supplierList: [],//供应商数组
      // ---------------------------------------比价采购操作数据-----------------------------------------------
      spareType: 0,// 0：设备列表   1：物料列表
      imageSrc: undefined,//图片预览参数
      ruleFormList: [], // 表格展示列表
      selectionList: [],// 勾选后的列表
      ImageOpen: false,
      /** 物料查询参数 --------------------------------------------------------------------------------- */
      AqueryParams: {
        materialNum: null,
        materialName: null,
        storehouseId: -1
      },
      /** 设备查询参数 --------------------------------------------------------------------------------- */
      BqueryParams: {
        equipmentName: null,
      },
      pageParams: {
        pageNum: 1,
        pageSize: 10,
        /** 列表默认排序字段 ---------------------------------------------------------------------------------------------------------- */
        // orderByColumn: 'purchaseId',
        /** ------------------------------------------------------------------------------------------------------------------------- */
        isAsc: 'desc'
      },
      pagination: {
        total: 1,
        pageCount: 1
      },
      /** 表单规则 --------------------------------------------------------------------------------------------------------------------- */
      rules: {}
      /** ----------------------------------------------------------------------------------------------------------------------------- */
    }
  },
  updated () {
    this.$nextTick(() => {
      if (this.ruleForm.faultLevel) {
        return
      } else {

        this.ruleFormList.forEach(outerItem => {
          this.parlist.forEach(item => {
            if (this.spareType) {
              if (outerItem.consumableBaseId == item.consumableBaseId) {
                this.$refs.listPowerSupplyTab.toggleRowSelection(outerItem, true);
              }
            } else {
              if (outerItem.equipmentName == item.equipmentName) {
                this.$refs.listPowerSupplyTab.toggleRowSelection(outerItem, true);
              }
            }
          })
        })
      }
    })
  },
  methods: {
    dialogwidth () {
      if (this.ruleForm.faultLevel) {
        return '780px'
      } else {
        return '1400px'
      }
    },
    // 查看图片
    handleSelectImage (src) {
      this.imageSrc = src
      this.ImageOpen = true
    },
    // 打开表单对话框
    openDialog (value) {
      this.spareType = value
      this.refreshList(value)
      this.dialogVisible = true
    },
    // -----------------------------------------------------------------系统内采购：开始-------------------------
    refreshList (type) {
      if (type == 1) {
        //物料采购列表接口-----------------------
        const params = processQueryParams(this.AqueryParams, this.pageParams)
        replacementList(params).then((res) => {
          this.pagination.total = res.total
          this.pagination.pageCount = pageCount(this.pagination.total, this.pageParams.pageSize)
          this.ruleFormList = res.data
        })
      } else if (type == 0) {
        //设备采购列表接口----------------------
        const params = processQueryParams(this.BqueryParams, this.pageParams)
        equipmentList(params).then((res) => {
          this.pagination.total = res.total
          this.pagination.pageCount = pageCount(this.pagination.total, this.pageParams.pageSize)
          this.ruleFormList = res.data
        })
      }
    },
    // 查询事件-----------------------------------------------------
    handleQueryClick () {
      this.refreshList(this.spareType)
    },
    // 分页器事件-----------------------------
    handleSizeChange (value) {
      this.pageParams.pageSize = value
      this.refreshList(this.spareType)
    },
    handleCurrentChange (value) {
      this.pageParams.pageNum = value
      this.refreshList(this.spareType)
    },
    // 多选事件------------------------------------
    handleSelectionChange (val) {
      this.selectionList = val
    },
    // 重置事件----------------------------------------------------
    handleReset () {
      if (this.spareType == 1) {
        for (const key in this.AqueryParams) {
          this.AqueryParams[key] = ''
        }
      } else if (this.spareType == 0) {
        for (const key in this.BqueryParams) {
          this.BqueryParams[key] = ''
        }
      }
      this.pageParams.pageNum = 1
      this.refreshList(this.spareType)
    },
    // 提交事件-----------------------------------------------------------------
    handleSubmit () {
      let arr = [...this.selectionList, ...this.parlist]
      const newArr = arr.map(item => {
        if (this.spareType) {
          return item.materialName
        } else {
          return item.equipmentName
        }
      })
      const isRepeat = newArr.some((x, index, arr) => arr.findIndex(y => y == x) != index);
      if (isRepeat) {
        this.$message({
          message: '请勿重复添加采购品！',
          type: 'warning'
        });
        return
      }
      this.$emit('click_create_submit', { selectionList: this.selectionList, type: this.ruleForm.faultLevel })
      this.dialogVisible = false
      this.pageParams.pageNum = 1
    },
    // -----------------------------------------------------------------系统内采购：结束-------------------------


    //------------------------------------------------------------------ 系统外采购：开始-----------------------------

    // 系统外采购，设备的新增操作
    handleparentindexb (obj) {
      this.$emit('click_create_submit', { selectionList: [obj], type: this.ruleForm.faultLevel })
      this.handleClose()

    },
    // 系统外采购，物料的新增操作
    handleparentindexa (obj) {
      this.$emit('click_create_submit', { selectionList: [obj], type: this.ruleForm.faultLevel })
      this.handleClose()
    },
    //------------------------------------------------------------------ 系统外采购：结束-----------------------------
    /** ---------------------------------------------------------------------------------------------------------------------------------------- */
    // 关闭窗口，重置表单
    handleClose () {
      this.dialogVisible = false
      this.ruleForm.faultLevel = 0
    },
  }
}
</script>
<style lang="scss" scoped>
.form {

  .inventory {
    display: flex;
  }
}

::v-deep .el-input-number__decrease {
  display: none;
}

::v-deep .el-input-number__increase {
  display: none;
}

::v-deep .el-select {
  width: 100%;
}

::v-deep .el-input-number {
  width: 100%;
}

.dialog_footer {
  display: flex;
  justify-content: center;
}

.search_continer {
  padding: 10px;
  margin-bottom: 20px;
  display: flex;
  background-color: white;
  border-radius: 5px;

  &_title {
    line-height: 36px;
    padding: 0 20px 0 0;
    font-weight: bold;
  }

  &_myInput {
    padding-right: 20px;
  }
}

.operation_continer {
  padding: 10px;
  margin-bottom: 20px;
  display: flex;
  background-color: white;
  border-radius: 5px;

  &_title {
    line-height: 36px;
    padding: 0 20px 0 0;
    font-weight: bold;
  }
}

.table_continer_pagination {
  margin-bottom: 35px;
}
</style>
